<template>
  <el-card class="box-card">
    <itable
    :table="tconfig1.tableConfig"
    :tableData="tconfig1.tableData"
    :showform="false"
    :page-bean="tconfig1.pageBean"
    @pageChange="pageChange"
    @handleEdit="handleEdit"
    @handleDel="handleDel"
    >
      <template #searchBox>
        <Eform
          :model="form"
          :elem="fromData"
          :submit="true"
          :reset="true"
          :button="false"
          okIcon="Search"
          btnSize="default"
          submitText="搜索"
          @onSuccess="onSuccess"
          @onReset="onReset"
          >
        </Eform>
      </template>
      <template #type="prop">{{ prop.obj.row.type == 1 ? '单选' : '判断' }}</template>
      <template #options="prop">
        <div v-if="prop.obj.row.options?.length !== 0">
          <span v-for="(item, index) in prop.obj.row.options" :key="index">{{ item.number }}:{{ item.content }}&nbsp;&nbsp;</span>
        </div>
        <div v-else>-</div>
      </template>
      <template #headerbtn>
        <el-button type="primary" plain @click="clickadd" icon="Plus">添加</el-button>
      </template>
    </itable>

    <el-dialog
    :title="title == 0?'新增':'编辑'"
    v-model="dialogVisible"
    :before-close="handleClose"
    width="50%">
    <el-form :model="dform" :rules="drules" label-width="80px" ref="ruleFormRef">
      <el-form-item label="内容形式" prop="type">
        <el-radio-group v-model="dform.type" @change="changeradio">
          <el-radio :label="1" size="large" v-if="title == 0 ? true : dform.type == 1">单 选</el-radio>
          <el-radio :label="2" size="large" v-if="title == 0 ? true : dform.type == 2">判 断</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题干内容" prop="question">
        <el-input v-model="dform.question" clearable/>
      </el-form-item>
      <el-form-item label="正确答案" prop="question">
        <el-select v-model="dform.answer" placeholder="请选择正确答案">
          <el-option
            v-for="item in dform.optionspcode"
            :key="item.number"
            :label="item.number"
            :value="item.number">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选项">
        <div style="width: 100%;display: flex;justify-content: end;padding-bottom:10px;">
          <el-form-item><el-button type="primary" plain :icon="Plus" @click="addoption" v-if="dform.type == 1">新增选项</el-button></el-form-item>
        </div>
        <el-form-item
          v-for="(domain, index) in dform.optionspcode"
          :key="domain.number"
          :label="domain.number"
          :prop="'optionspcode.' + index + '.content'"
          style="marginBottom:25px"
          :rules="{
            required: true,
            message: `请补全${domain.number}选项内容`,
            trigger: 'blur',
          }"
        >
        <el-input v-model="domain.content"><template #append v-if="dform.type == 1"><el-icon style="cursor: pointer;" @click.prevent="removeDomain(domain)"><Delete /></el-icon></template></el-input>
      </el-form-item>
    </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
          <el-button @click="clickCancel(ruleFormRef)">取 消</el-button>
          <el-button type="primary" @click="clickComfig(ruleFormRef)">保 存</el-button>
      </span>
  </template>
  </el-dialog>
  </el-card>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue';
import itable from '@/components/table/table.vue'
import { PageBean } from "@/utils/page-bean";
import Eform from '@/components/eform/index.vue';
import { Plus } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import useCurrentInstance from '@/utils/useCurrentInstance'

const { proxy } = useCurrentInstance()
let option = ref([])
let title = ref(0)
let dialogVisible = ref(false)
let ruleFormRef = ref()
let fromData = reactive([
  {
    label: "题干内容",
    prop: "keyword",
    clearable: true,
  },
  {
    label: "题型",
    prop: "type",
    element:'select',
    option:[
      {label:'全部',value:''},
      {label:'单选',value:'1'},
      {label:'判断',value:'2'},
    ],
    clearable: true,
  }
])
let form = reactive({
  page: 1,
  size: 10,
  keyword:'',
  type:''
})

let drules = reactive({
  type:[
    { required: true, message: '请选择内容形式', trigger: 'blur' },
  ],
  question:[
    { required: true, message: '请填写题干', trigger: 'blur' },
  ]
})
let dform = reactive({
  type:1,
  id:'',
  question:'',
  answer:'',
  optionspcode:[{number: 'A',content: ''},{number: 'B',content: ''},{number: 'C',content: ''},{number: 'D',content: ''}]
})
const tconfig1 = reactive({
  tableConfig: {} as {loading:boolean,[propName:string]:any},
  tableData: [] as any[],
  pageBean: new PageBean(10, 1, 0),
})
// 重置
const onReset = () => {
  tconfig1.pageBean.pageIndex = 1
  getPositionAssault()
}
// 搜索
const onSuccess = () => {
  tconfig1.pageBean.pageIndex = 1
  getPositionAssault()
}

// 新增
const clickadd = () => {
  title.value = 0
  dialogVisible.value = true
}

// 弹框-提交
const clickComfig = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      delete dform.options
      if(title.value == 0){
        proxy.$api.getQuestionCreate(Object.assign(dform,{options:dform.optionspcode})).then(res => {
          if(res.code == 200){
            proxy.$message({
              type:'success',
              message:res.msg
            })
            getPositionAssault()
            dialogVisible.value = false
          }
        })
      }else{
        proxy.$api.getQuestionUpdate(Object.assign(dform,{options:dform.optionspcode})).then(res => {
          if(res.code == 200){
            proxy.$message({
              type:'success',
              message:res.msg
            })
            getPositionAssault()
            dialogVisible.value = false
          }
        })
      }
      dform.question = ''
      dform.type = 1
      dform.id = ''
      resetdata()
    } else {
      return false
    }
  })
}
const changeradio = (val) => {
  if(val == 2){
    dform.optionspcode = [{number:'A',content:'正确'},{number:'B',content:'错误'}]
  }else{
    resetdata()
  }
}
const removeDomain = (item) => {
  const index = dform.optionspcode.indexOf(item)
  if (index !== -1) {
    dform.optionspcode.splice(index, 1)
  }
}
const addoption = () => {
  let letter = 'A,B,C,D,E,F'
  if(dform.optionspcode.length >= 6){
    proxy.$message({
      type:'warning',
      message:'最多仅可添加六道选项!'
    })
  }else{
    dform.optionspcode.push({number:letter.split(',')[dform.optionspcode.length],content:''})
  }
}
// 弹框-取消
const clickCancel = (formEl) => {
  if (!formEl) return
  dialogVisible.value = false
  formEl.resetFields()
  dform.question = ''
  dform.type = 1
  dform.id = ''
  resetdata()
}
const handleClose = () => {
  ruleFormRef.value.resetFields()
  dform.question = ''
  dform.type = 1
  dform.id = ''
  resetdata()
  dialogVisible.value = false
}
const resetdata = () => {
  dform.optionspcode = [{number: 'A',content: ''},{number: 'B',content: ''},{number: 'C',content: ''},{number: 'D',content: ''}]
}
// 表格-编辑
const handleEdit = (a, b, id) => {
  title.value = 1
  dialogVisible.value = true
  dform.question = b.question
  dform.type = b.type
  dform.answer = b.answer
  dform.id = b.id
  dform.optionspcode = b.type == 2 ? [{number:'A',content:'正确'},{number:'B',content:'错误'}] : b.options
}
// 表格-删除
const handleDel = (a, b, id) => {
  ElMessageBox.confirm(
    '此操作将永久删除该数据,是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    proxy.$api.getQuestionDelete({id:b.id}).then(res => {
      if(res.code == 200){
          proxy.$message({
            type: 'success',
            message: res.msg,
          })
          getPositionAssault()
        }
    })
  })
  .catch(() => {
    proxy.$message({
      type: 'info',
      message: '已取消删除',
    })
  })
}
// 分页
const pageChange = () => {
  getPositionAssault()
}

// 题目列表
const getPositionAssault = () => {
  tconfig1.tableConfig.loading = true
  form.page = tconfig1.pageBean.pageIndex
  proxy.$api.getQuestionLists(form).then(res => {
    tconfig1.pageBean.Total = res.result.total_rows,
    tconfig1.tableData = res.result.lists
    tconfig1.tableConfig.loading = false
  }).catch(err => { tconfig1.tableConfig.loading = false })
}
getPositionAssault()
// 获取职位列表
const getPositionLists = () => {
  proxy.$api.getPositionLists({page:1,size:9999,name:''}).then(res => {
    option.value = res.result.lists
  }).catch(err => console.log(err))
}
getPositionLists()
// 初始化表格
const initTable = () => {
  tconfig1.tableConfig = {
  loading: true,
  hasSelect: false,
  hasIndex: false,
  hasOperation: true,
  hasSearch: true,
  hasPage: true,
  headerShowBtn:true,
  tr: [
    {
      label: "题目编号",
      prop: "id",
      sortable:true
    },
    {
      label: "题干内容",
      prop: "question",
    },
    {
      label: "题型",
      prop: "type",
      show:'template'
    },
    {
      label: "选项",
      width:'330',
      prop: "options",
      show:'template'
    }
  ],
  operation:{
    label:'操作',
    width:'330',
    data:[
      { label:'编辑', type:'', icon:'EditPen', Fun:'handleEdit', id: 1 },
      { label:'删除', type:'danger',icon:'Delete', Fun:'handleDel', id: 2 },
    ]
  }
}
}
initTable()
</script>

<style lang='scss' scoped>
:deep(.el-dialog__body){
.el-form>.el-form-item{
  // width: 60%;
  margin-bottom: 20px;
  margin-left: 10px;
}
.el-select{
  width: 100%;
}
}
.dialog-footer{
  width: 100%;
  display: flex;
  justify-content: center;
}
.el-alert{
  background-color: rgba(255, 255, 255, 0) !important;
}
</style>
